package org.amos.security;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.same.SaSameUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.utils.JsonUtils;
import org.amos.core.basic.vo.R;
import org.amos.security.properties.AuthFilterProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 代码方式进行配置
 *
 */
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(AuthFilterProperties.class)
@RequiredArgsConstructor
public class SaTokenAutoConfiguration implements WebMvcConfigurer {

    private final AuthFilterProperties properties;

    /**
     * 注册 Sa-Token 的拦截器，打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    }

    /**
     * 校验是否从网关转发
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/actuator/**")
                .setAuth(obj -> {
                    String serviceToken = SaHolder.getRequest().getHeader(SystemConstant.SYS_SERVICE_TOKEN_KEY);
                    if (StrUtil.isNotBlank(serviceToken)) {
                        return;
                    }
                    if (SaManager.getConfig().getCheckSameToken()) {
                        SaSameUtil.checkCurrentRequestToken();
                    }
                })
                .setError(e -> {
                    SaHolder.getResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
                    R<String> result = R.error(HttpStatus.UNAUTHORIZED.value(), "认证失败，无法访问系统资源");
                    return JsonUtils.objectToJson(result);
                });
    }
}
